package auth

import (
	"context"
	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"
	"fast-boot/app/model"
	"fast-boot/common/xerr"
	"github.com/hwUltra/fb-tools/jwtx"

	"github.com/zeromicro/go-zero/core/logx"
)

type MeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取个人信息
func NewMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MeLogic {
	return &MeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MeLogic) Me() (resp *types.MeResp, err error) {
	userId := jwtx.NewJwtX(l.ctx, l.svcCtx.Config.JwtUserKey).GetUid()
	gormDb := l.svcCtx.GormClient.GormDb
	userInfo := model.SysUserModel{}
	gormDb.Preload("Roles", "status = ?", 1).First(&userInfo, userId)

	if userInfo.Id == 0 {
		logx.WithContext(l.ctx).Errorf("用户不存在uid: %d", userId)
		return nil, xerr.NewErrMsg("用户不存在")
	}

	roleIds := make([]int64, 0)
	rolesCodes := make([]string, 0)
	for _, v := range userInfo.Roles {
		roleIds = append(roleIds, v.Id)
		rolesCodes = append(rolesCodes, v.Code)
	}
	//查询权限
	perms := make([]string, 0)
	gormDb.Model(&model.SysMenuModel{}).
		Joins("JOIN sys_role_menu on sys_menu.id = sys_role_menu.menu_id").
		Where("sys_role_menu.role_id IN ?", roleIds).
		Where("sys_menu.type = 4").
		Pluck("sys_menu.perm", &perms)

	return &types.MeResp{
		UserId:   userId,
		Nickname: userInfo.Nickname,
		Username: userInfo.Username,
		Avatar:   userInfo.Avatar,
		Roles:    rolesCodes,
		Perms:    perms,
	}, nil
}
